package com.egao.common.publicly;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.egao.common.component.elasticsearch.service.ElasticSearchService;
import com.egao.common.component.wechat.WeChatUtils;
import com.egao.common.core.Constants;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.security.JwtUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.system.entity.LoginRecord;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.LoginRecordService;
import com.egao.common.module.system.service.UserService;
import com.egao.common.publicly.entity.PubliclyCareerVO;
import com.egao.common.publicly.service.PubliclyMatchingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pyx
 */
@Api(tags = "推送匹配")
@RestController
@RequestMapping("${api}")
public class PubliclyMatchingController {

    @Autowired
    private PubliclyMatchingService publiclyMatchingService;
    @Autowired
    private ElasticSearchService elasticSearchService;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginRecordService loginRecordService;


    @ApiOperation("获取学生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "string", paramType = "query"),
    })
    @GetMapping("/publicly/matching/student")
    public JsonResult message(String code, HttpServletRequest request, HttpServletResponse response) {
        if(StrUtil.isBlank(code)){
            return JsonResult.error("参数为空");
        }

        String username = WeChatUtils.getStudent(code);
        if (StrUtil.isBlank(username)) {
            Console.error("企业号登录 未查询到用户");
            return JsonResult.error("未查询到用户");
        }
        User userDetails = userService.getByUsername(username);
        if (userDetails == null) {
            Console.error("企业号登录 未查询到用户!");
            return JsonResult.error("未查询到用户!");
        }
        userDetails = userService.selectUserAuth(userDetails);

        // 重新授权
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String access_token_new = JwtUtil.buildToken(username, Constants.TOKEN_EXPIRE_TIME, Constants.TOKEN_KEY);
        loginRecordService.saveAsync(username, LoginRecord.TYPE_REFRESH, "企业号登录", request);

        Map<String, String> map = new HashMap<>(1);
        map.put("access_token", access_token_new);
        map.put("xh", username);

        return JsonResult.ok().setData(map);
    }

    @ApiOperation("列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "学生id", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "标题", required = false, dataType = "String", paramType = "query"),
    })
    @GetMapping("/publicly/matching/list")
    public PageResult<PubliclyCareerVO> page(HttpServletRequest request) {
        PageParam<PubliclyCareerVO> pageParam = new PageParam<>(request);
        if ("0".equals(pageParam.getString("today"))) {
            String start = DateUtil.format(DateUtil.beginOfDay(new Date()), DatePattern.NORM_DATETIME_PATTERN);
            String end = DateUtil.format(DateUtil.endOfDay(new Date()), DatePattern.NORM_DATETIME_PATTERN);
            pageParam.put("pushDateStart", start);
            pageParam.put("pushDateEnd", end);
        }

        return new PageResult<>(publiclyMatchingService.listPage(pageParam), pageParam.getTotal());
    }

    @ApiOperation("详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "推送信息id", required = true, dataType = "int", paramType = "query"),
    })
    @OperLog(value = "推送匹配", desc = "查询详情")
    @GetMapping("/publicly/matching/details")
    public JsonResult details(Integer id){
        return publiclyMatchingService.getId(id);
    }

    @ApiOperation("明日宣讲会")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学生ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "date", value = "日期", required = true, dataType = "String", paramType = "query"),
    })
    @OperLog(value = "明日匹配宣讲会", desc = "明日匹配宣讲会")
    @GetMapping("/publicly/matching/preach")
    public JsonResult details(Integer id, String date) throws IOException {
        return elasticSearchService.searchTomorrowPreach(id, date);
    }
}
